package com.bdqn.zhang.action;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bdqn.zhang.pojo.Emp;
import com.bdqn.zhang.pojo.Picture;
import com.bdqn.zhang.pojo.Sysuser;
import com.bdqn.zhang.service.UserService;
import com.bdqn.zhang.util.LayData;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Namespace("/")
@ParentPackage("default")
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<Sysuser> {

    //此处必须实例化
    private Sysuser user = new Sysuser();


    /*设置分页参数*/
    private Integer limit;
    private Integer page;

    public Integer getLimit() {
        return limit;
    }

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }


    /*设置文件上传参数*/

    private File file;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    private String savePath;

    public String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }


    private String fileFileName;

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    private String fileContentType;

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }





    /*文件下载属性*/
    private String fileName;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    private String conetntType;

    //读取下载文件的输入流
    private InputStream inputStream;

    public String getConetntType() {
        return conetntType;
    }

    public void setConetntType(String conetntType) {
        this.conetntType = conetntType;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    /*定义异步返回结果*/
    private String result;

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    @Override
    public Sysuser getModel() {
        return user;
    }

    @Resource
    private UserService userService;


    @Action(value = "login", results = {@Result(name = "success", type = "json", params = { "root", "result" }) })
    public String login(){
        Sysuser u = userService.findUser(this.user.getUsername(),this.user.getPassword());
        if(u != null){
            ServletActionContext.getRequest().getSession().setAttribute("username",u.getUsername());
            result = "true";
        } else {
            result = "false";
        }
        return "success";
    }

    @Action(value = "toindex", results = {@Result(name = "success", location = "/WEB-INF/jsp/index.jsp") })
    public String toindex(){
        return "success";
    }


    @Action(value = "emplist", results = {@Result(name = "success", type = "json", params = { "root", "result" }) })
    public String list(){
        List<Emp> emps = userService.getAllEmps(limit,page);
        Long count = userService.getCount();
        LayData laydata = LayData.data(count.intValue(), emps);
        result = JSONObject.toJSONString(laydata, SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteNullNumberAsZero);
        return "success";
    }

    @Action(value = "toadd", results = {@Result(name = "success", location = "/WEB-INF/jsp/add.jsp") })
    public String toadd(){
        return "success";
    }

    @Action(value = "upload", params = {"savePath","D:/upload/"}, results = {@Result(name = "success", type = "json", params = { "root", "result" }) })
    public String upload() throws Exception{

        /*String uploadPath = "D:/upload/";*/
        FileInputStream fis= null;
        FileOutputStream fos= null;
        try {
            byte[] buffer=new byte[1024];
            fis = new FileInputStream(this.getFile());
            String picPath = this.getSavePath()+ UUID.randomUUID().toString().replace("-","")+this.getFileFileName().substring(this.getFileFileName().lastIndexOf("."),this.getFileFileName().length());
            fos = new FileOutputStream(picPath);

            int length=fis.read(buffer);
            while (length>0) {
                //每次写入length长度的内容
                fos.write(buffer,0, length);
                length=fis.read(buffer);
            }
            result = JSONObject.toJSONString("true");
            userService.addPicture(new Picture(picPath));
        } catch (IOException e) {
            e.printStackTrace();
            result = JSONObject.toJSONString("false");
        } finally {
            fis.close();
            fos.flush();
            fos.close();
        }

        return "success";
    }

    @Action(value = "toPicList", results = {@Result(name = "success", location = "/WEB-INF/jsp/picList.jsp") })
    public String toPicList(){
        return "success";
    }

    @Action(value = "picList", results = {@Result(name = "success", type = "json", params = { "root", "result" } )})
    public String getPicList(){
        List<Picture> pictures = userService.getAllPics(limit,page);
        Long count = userService.getPicsCount();
        LayData laydata = LayData.data(count.intValue(), pictures);
        result = JSONObject.toJSONString(laydata);
        return "success";
    }

    @Action(value = "download", results = {@Result(name = "success", type = "stream", params ={"contentType","application/octet-stream"})})
    public InputStream downloadPic() throws Exception{
        String path = this.getFileName();
        return new BufferedInputStream(new FileInputStream(path));
    }
}


